import React, { useState } from 'react'
import { Input, TextArea, ImageUploader, Button, Grid, Space } from 'antd-mobile'
import { DndContext, closestCenter } from '@dnd-kit/core'
import { SortableContext, useSortable } from '@dnd-kit/sortable'
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import { sleep } from 'antd-mobile/es/utils/sleep'

export const demoSrc =
  'https://images.unsplash.com/photo-1567945716310-4745a6b7844b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60'

export async function mockUploadFail() {
  await sleep(200)
  throw new Error('Fail to upload')
}
// 由于 @dnd-kit/utilities 没有 arrayMove 导出，手动实现该函数
// 原代码无明显意外标记问题，推测指令可能有误，此处保持原代码不变
const arrayMove = (array: any, fromIndex: number, toIndex: number) => {
  const newArray = [...array]
  const [removed] = newArray.splice(fromIndex, 1)
  newArray.splice(toIndex, 0, removed)
  return newArray
}

type ImageItem = {
  id: string
  url: string
  file: File
}

const NoteEdit: React.FC = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [images, setImages] = useState<ImageItem[]>([
    {
      id: '1',
      url: demoSrc,
      file: new File([], demoSrc)
    },
    {
      id: '2',
      url: demoSrc,
      file: new File([], demoSrc)
    }
  ])
  const [fileList, setFileList] = useState<ImageUploadItem[]>([
    {
      url: demoSrc
    }
  ])
  async function mockUpload(file: File) {
    await sleep(200)
    let imgs = [...images, { id: Date.now().toString(), url: URL.createObjectURL(file), file }]
    setImages(imgs)
    return {
      url: URL.createObjectURL(file)
    }
  }

  const handleUpload = (file: File) => {
    const url = URL.createObjectURL(file)
    setImages(prev => [...prev, { id: Date.now().toString(), url, file }])
    return { url }
  }

  const handleDeleteImage = (id: string) => {
    setImages(prev => prev.filter(img => img.id !== id))
  }

  const handleDragEnd = (event: any) => {
    const { active, over } = event
    if (active.id !== over?.id) {
      setImages(prev => {
        const oldIndex = prev.findIndex(img => img.id === active.id)
        const newIndex = prev.findIndex(img => img.id === over?.id)
        return arrayMove(prev, oldIndex, newIndex)
      })
    }
  }

  return (
    <div style={{ padding: 16 }}>
      <Space direction='vertical' block>
        <div style={{ marginBottom: 8 }}>文章标题</div>
        <Input placeholder='请输入文章标题' value={title} onChange={setTitle} maxLength={50} />

        <div style={{ marginBottom: 8 }}>文章内容</div>
        <TextArea placeholder='请输入文章内容' value={content} onChange={setContent} rows={5} maxLength={500} />

        <ImageUploader value={fileList} onChange={setFileList} upload={mockUpload as any} />

        <Button color='danger' block style={{marginTop:'20px'}}>
          发布
        </Button>
      </Space>
    </div>
  )
}

export default NoteEdit
